#include <iostream>
#include <stdio.h>
#include <unistd.h>
//#include <mysql/mysql.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
using namespace std;

#define BUF_SIZE 550
pid_t send_fork=0;
int p_arr[2],sd=0,send_len=0,recv_len=0;
struct sockaddr_in cli,addr;
char send_buf[BUF_SIZE], recv_buf[BUF_SIZE];
socklen_t addr_len=sizeof(addr),cli_len= sizeof(cli);
void send_task(){
	int tmp=0;
	struct sockaddr_in c;		//用于接收管道指针
	socklen_t c_len=0;
	c_len=sizeof(c);
	read(p_arr[0],(void*)&c,(size_t)c_len);
//	c=&tmp;
	printf("拿到客户端socket\n");
    	for(;;){	
		memset(send_buf,0,sizeof(send_buf));
		cin>>send_buf;
		printf("手动发送：%s\n",send_buf);
		sendto(sd,&send_buf,strlen(send_buf),0,(struct sockaddr*)&c,c_len);		
    	}
}  

int main() {
	pipe(p_arr);
    sd=socket(AF_INET,SOCK_DGRAM,0);
    if(0>sd){
        cout<<"create socket error"<<endl;
        return -1;
    }
    addr.sin_family=AF_INET;
  //  addr.sin_addr.s_addr=inet_addr("127.0.0.1");
    addr.sin_port=htons(30026);

    if(0>bind(sd,(sockaddr*)&addr,sizeof(addr))) {
        printf("bind error\r\n");
        return -1;
    }
  

    //send_len=sprintf(send_buf,"%s","Hello Client I'm Server : ");
    int t=0,s=0;

	send_fork=fork();
	if(send_fork==0){
		send_task();

	}

    for(;;){
        memset(recv_buf,0,BUF_SIZE);
        recv_len=recvfrom(sd,&recv_buf,BUF_SIZE,0,(struct sockaddr*)&cli,&cli_len);
        write(p_arr[1],(void*)&cli,(size_t)cli_len);
	//printf("\n-------->\n%s\n---->\n",recv_buf);
	
        for(int i=0;i<recv_len;i++){
            printf("%02x",recv_buf[i]);
		}
        printf("\n---->\r\n");
	
        t++;
        send_len=sprintf(&send_buf[0],"I receiveid %d data your sent: <%s>\n",t,recv_buf);
        sendto(sd,&send_buf,send_len,0,(struct sockaddr*)&cli,cli_len);
        if(0>recv_len)
              break;
    }
    close(sd);
    cout << "disconnect" <<endl;
    return 0;
}
